package com.warf.warftool;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.tanukisoftware.wrapper.WrapperListener;
import org.tanukisoftware.wrapper.WrapperManager;

import com.warf.warftool.utils.WarfUtils;
import com.warf.warftool.was.WasDeploy;
import com.warf.warftool.was.WasScriptExecution;

public class WarfDeployExecutionMain implements WrapperListener{
	String appName="";
	String earFile ="";
	String warFile ="";
	boolean install=false;
	boolean update=false;
	boolean remove=false;
	String path="";
	String host="";
	String port="";
	String username="";
	String password="";
	private Properties warfProperties;
	
	private WarfDeployExecutionMain(){
		
	}
	@Override
	public void controlEvent(int event) {
		// TODO Auto-generated method stub
		 if ( ( event == WrapperManager.WRAPPER_CTRL_LOGOFF_EVENT )
	                && ( WrapperManager.isLaunchedAsService() || WrapperManager.isIgnoreUserLogoffs() ) )
	        {
	                // Ignore
	        }
	        else
	        {
	                WrapperManager.stop( 0 );
	                // Will not get here.
	        }

	}

	@Override
	public Integer start(String[] arg0) {
		// TODO Auto-generated method stub
		CommandLineParser parser= new DefaultParser();
		
		Options options=createOptions();
		
		try{
			CommandLine line= parser.parse(options, arg0);
			if(arg0.length < 1){
				showHelp(options);
				return -1;
			}
			if(line.hasOption("h") || line.hasOption("help")){
				showHelp(options);
				return null;
			}
			
			String[] argList=line.getArgs();
			if(argList.length < 1){
				System.out.println("AppName is Undefined");
				showHelp(options);
				return -1;
			}
			else{
				appName=argList[0];
			}
			System.out.println("line: "+line.getArgList());
			if(line.hasOption('e')){
				earFile=line.getOptionValue('e');
				
			}
			if(line.hasOption('w')){
				warFile=line.getOptionValue('w');
				
			}
			if(line.hasOption("install")){
				install=true;
			}
			if(line.hasOption("update")){
				update=true;
			}
			if(line.hasOption("remove")){
				remove=true;
			}
			if(line.hasOption("path")){
				path=line.getOptionValue("path");
				
			}
			if(line.hasOption("host")){
				host=line.getOptionValue("host");
				
			}
			if(line.hasOption("port")){
				port=line.getOptionValue("port");
				
			}
			if(line.hasOption("user")){
				username=line.getOptionValue("user");
				
			}
			if(line.hasOption("password")){
				password=line.getOptionValue("password");
				
			}
			
			warfProperties = new Properties();
			try {
				warfProperties.load(WarfDeployMain.class.getClassLoader().getResourceAsStream(WarfUtils.WARF_PROPERTIES_FILE));
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				System.err.println(WarfUtils.WARF_PROPERTIES_FILE+" not Found");
				warfProperties= null;
			} catch (IOException e) {
				System.err.println(WarfUtils.WARF_PROPERTIES_FILE+" load Exception");
				warfProperties= null;
			}
			
			if(host.equalsIgnoreCase("")||port.equalsIgnoreCase("") ){
				System.out.println("Try to load Configuration values from WARF Configuration properties");
				if(warfProperties != null){
					deployByProperty();
				}
				
			}else{
				deploy();
			}
			
				
		}catch( ParseException exp){
			showHelp(options);
		}
		
		
		return null;
	}
	
	public void deployByProperty(){
		if(!appName.equalsIgnoreCase("") && warfProperties != null){	
			WasDeploy wasDeploy = new WasDeploy(appName, "");
			wasDeploy.setEarfiles(earFile);
			wasDeploy.setWarfiles(warFile);
			wasDeploy.run();
		}
	}
	
	public void deploy(){
		if(!appName.equalsIgnoreCase("")){
			System.out.println("Deploy Method: Appname:"+appName);
			System.out.println("Deploy Method: earFile:"+earFile);
			System.out.println("Deploy Method: warFile:"+warFile);
			System.out.println("Deploy Method: install:"+install);
			
			WasDeploy wasDeploy = new WasDeploy(appName);
			wasDeploy.setDmgrHostName(host);
			wasDeploy.setDmgrPortName(port);
			wasDeploy.setDmgrUsername(username);
			wasDeploy.setDmgrPortName(password);
			wasDeploy.setEarfiles(earFile);
			wasDeploy.setWarfiles(warFile);
			wasDeploy.setEarPath(path);
			if(install){
				wasDeploy.setInstallType("install");
			}else if(update){
				wasDeploy.setInstallType("update");
			}else if(remove){
				wasDeploy.setInstallType("remove");
			}
			wasDeploy.run();
			
		}
				
		
	}
	public static void showHelp(Options options){
		HelpFormatter formatter = new HelpFormatter();
		formatter.printHelp("WARFDeploy [OPTIONS] [WARFName]", options);
	}
	
	public static Options createOptions(){
		Options options = new Options();
		options.addOption("h", "help", false, "Print this Message");
		options.addOption("install",false, "Install the WAR/EAR File");
		options.addOption("update",false, "Install the WAR/EAR File");
		options.addOption("remove",false, "Install the WAR/EAR File");
		options.addOption("path",true, "WAR/EAR File Path");
		options.addOption("e","ear", true, "Name of the Ear File");
		options.addOption("w","war", true, "Name of the WAR file");
		options.addOption("host", true, "Dmgr host Name");
		options.addOption("port", true, "Dmgr SOAP Port");
		options.addOption("user", true, "Dmgr Security Username");
		options.addOption("password", true, "Dmgr Security Password");
		return options;
	}

	@Override
	public int stop(int exitCode) {
		// TODO Auto-generated method stub
		return exitCode;
	}
	
	public static void main( String[] args ){
		
		WrapperManager.start( new WarfDeployExecutionMain(), args );

	 }


}
